<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list" style="width: 100%">
              <!-- type:index会自动生成序号 -->
              <el-table-column label="序号" type="index" width="50" />
              <el-table-column prop="name" label="角色名称" width="180" />
              <el-table-column prop="description" label="描述" />
              <el-table-column width="300" label="操作">
                <template #default="{row}">
                  <el-button size="mini" type="success" @click="assignPer(row.id)">分配权限</el-button>
                  <el-button size="mini" type="primary" @click="hEdit(row.id)">编辑</el-button>
                  <el-button size="mini" type="danger" @click="hDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 新增弹框 -->
            <el-dialog
              :title="isEdit?'编辑':'新增'"
              :close-on-click-modal="false"
              :close-on-press-escape="false"
              :visible.sync="showDialog"
              @close="hClose"
            >
              <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
                <el-form-item label="角色名称" prop="name">
                  <el-input v-model="roleForm.name" />
                </el-form-item>
                <el-form-item label="角色描述" prop="description">
                  <el-input v-model="roleForm.description" />
                </el-form-item>
              </el-form>
              <!-- 底部 -->
              <el-row slot="footer" type="flex" justify="center">
                <el-col :span="6">
                  <el-button size="small" @click="showDialog =false">取消</el-button>
                  <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
                </el-col>
              </el-row>
            </el-dialog>
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="q.page"
                :page-sizes="[2, 3, 5, 10,20]"
                :page-size="q.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 分配角色弹框 -->
      <el-dialog
        title="新增"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showPerDialog"
      >
        <assignPer :role-id="roleId" @close="showPerDialog = false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoles, delRole, addRole, getRoleById, updateRoleById } from '@/api/settings'
import assignPer from './assignPermission.vue'
export default {
  components: { assignPer },
  data() {
    return {
      roleId: '',
      showPerDialog: false, // 控制分配角色弹框的显示与隐藏
      showDialog: false, // 控制弹窗的显示与隐藏
      isEdit: false, // 控制是编辑状态还是新增状态
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      },
      list: [], // 所有角色的信息
      total: 0, // 所有角色信息的总数
      q: {
        page: 1,
        pagesize: 2
      }
    }
  },
  created() {
    this.loadRoles() // 调用获取所有角色信息
  },
  methods: {
    assignPer(id) {
      this.roleId = id
      this.showPerDialog = true
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.q.pagesize = val
      this.loadRoles()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.q.page = val
      this.loadRoles()
    },
    // 重置表单
    hClose() {
      this.$refs.roleForm.resetFields()
    },
    // 新增角色
    hAdd() {
      this.showDialog = true
      this.isEdit = false
    },
    // 封装一个新增角色的函数
    async doAdd() {
      try {
        const res = await addRole(this.roleForm)
        // console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.loadRoles()
        this.total++
        const maxPage = Math.ceil(this.total / this.q.pagesize)
        this.q.page = maxPage
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑角色
    hEdit(id) {
      this.showDialog = true
      this.isEdit = true
      this.getRoleById(id)
    },
    // 根据ID获取点击的内容
    async getRoleById(id) {
      try {
        const res = await getRoleById(id)
        this.roleForm = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 封装修改角色信息的函数
    async doEdit() {
      try {
        const res = await updateRoleById(this.roleForm)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.loadRoles()
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    // 确定键,发送内容
    hSubmit() {
      this.$refs.roleForm.validate((valid) => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 删除角色
    hDel(id) {
      this.$confirm('您确定要删除此内容吗').then(async() => {
        const res = await delRole(id)
        // console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        if (this.list.length === 1) {
          this.q.page--
          if (this.q.page <= 0) {
            this.q.page = 1
          }
        }
        this.loadRoles()
      }).catch(error => error)
    },
    // 获取所有角色信息
    async loadRoles() {
      try {
        const res = await getRoles(this.q)
        // console.log(res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

